import React from 'react';
import { connect } from 'dva/index';
import { Button, Col, DatePicker, Form, Input, InputNumber, Modal, Row, Select, Switch } from 'antd';
import PortSelect from '../../common/portSelect'
import moment from 'moment'
import { route } from 'react-router/lib/PropTypes';

const dateFormat = 'YYYY-MM-DD';
const R = require("ramda");
const FormItem = Form.Item;
const freightFeeDetail = Form.create()(class FreightFeeDetail extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            open: false,
            disabled: false
        }
    }

    handleOpen = (disabled) => {
        this.setState({ open: true, disabled });
    }

    handleCancel = () => {
        this.setState({ open: false });
        this.props.form.resetFields();
    }

    handleConfirm = () => {
        this.props.form.validateFields({ force: true }, (errors, values) => {
            if (errors) return;
            values.id = this.props.freightFee.dataSource && this.props.freightFee.dataSource.id ? this.props.freightFee.dataSource.id : null;
            values.airlineId = parseInt(values.airlineId);
            values.loadingPort = parseInt(values.loadingPort);
            values.destinationPort = parseInt(values.destinationPort);
            values.transitPort = values.transitPort ? parseInt(values.transitPort) : 0;
            values.berthingId = parseInt(values.berthingId);
            values.supplierId = parseInt(values.supplierId);
            values.begindate = R.isNil(values.begindate) || R.isEmpty(values.begindate) ? "" : values.begindate.format(dateFormat);
            values.enddate = R.isNil(values.enddate) || R.isEmpty(values.enddate) ? "" : values.enddate.format(dateFormat);
            values.share = values.share ? '0' : '1';
            // console.log(R.pick(Object.keys(values), this.props.freightFee.dataSource));
            // console.log(values);
            if (!R.equals(R.pick(Object.keys(values), this.props.freightFee.dataSource), values)) {
                this.props.dispatch({
                    type: R.isNil(values.id) ? 'freightFee/addFreightFee' : 'freightFee/updateFreightFee',
                    payload: {
                        ...values,
                        onSuccess: () => {
                            this.handleCancel();
                            if (this.props.refreshList) this.props.refreshList();
                        }
                    }
                })
            } else this.handleCancel();
        });
    }


    handleChange = (value) => {
        let form = this.props.form;
        let dataList = this.props.airline.airlineList ? this.props.airline.airlineList : [];
        for (let i in dataList) {
            let item = dataList[i];
            if (item.id == value) {
                this.props.dispatch({
                    type: "airline/getAirlineIdPorts",
                    payload: {
                        airlineId: value,
                        onSuccess: () => { }
                    }
                })
            }

        }
    };

    onChangeTransit = (value) => {
        if (value === "2") this.props.form.setFieldsValue({ transitPort: undefined })
    }

    render() {
        let dataSource = this.props.freightFee.dataSource ? this.props.freightFee.dataSource : {};
        let supplierList = this.props.supplier.supplierList ? this.props.supplier.supplierList : [];
        let airlineList = this.props.airline.airlineList ? this.props.airline.airlineList : [];
        let loadingPortList = this.props.airline.loadingPortList ? this.props.airline.loadingPortList : [];
        let destinationPortist = this.props.airline.destinationPortist ? this.props.airline.destinationPortist : [];

        let berthingCompanyList = this.props.berthingCompany.berthingCompanyList ? this.props.berthingCompany.berthingCompanyList : [];
        let formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 14 } };
        let layout = { labelCol: { span: 4 }, wrapperCol: { span: 19 } };
        const { getFieldDecorator } = this.props.form;
        let footer = [
            <Button key="save" size="large" loading={this.props.loading} onClick={this.handleConfirm.bind(this)}
                style={{ display: this.state.disabled ? 'none' : 'inline-block' }}>保存</Button>,
            <Button key="cancel" size="large" loading={this.props.loading}
                onClick={this.handleCancel.bind(this, true)}>{this.state.disabled ? "关闭" : "取消"}</Button>
        ];

        return (
            <Modal maskClosable={false} visible={this.state.open} width={850} title={"运费详情"}
                confirmLoading={this.props.loading} onCancel={this.handleCancel.bind(this)} footer={footer}>
                <Form>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="供应商代码" hasFeedback>
                                {getFieldDecorator('supplierId', {
                                    rules: [{
                                        required: true, message: '请选择供应商代码'
                                    }],
                                    initialValue: (R.isNil(dataSource.supplierId) || R.isEmpty(dataSource.supplierId)) ? undefined : dataSource.supplierId + ""
                                })(
                                    <Select style={{ width: '100%' }} disabled={this.state.disabled} showSearch
                                        placeholder="可通过输入关键字搜索"
                                        filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>
                                        {
                                            !R.isNil(supplierList) ? supplierList.map(item => {
                                                return (<Select.Option value={item.id + ""}
                                                    key={item.id + ""}>{item.supplierCode}</Select.Option>);
                                            }) : ''
                                        }
                                    </Select>
                                    )}
                            </FormItem>
                        </Col>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="航线代码" hasFeedback>
                                {getFieldDecorator('airlineId', {
                                    rules: [{
                                        required: true, message: '请选择航线代码'
                                    }],
                                    initialValue: (R.isNil(dataSource.airlineId) || R.isEmpty(dataSource.airlineId)) ? undefined : dataSource.airlineId + ""
                                })(
                                    <Select style={{ width: '100%' }} disabled={this.state.disabled} showSearch
                                        placeholder="可通过输入关键字搜索" onChange={this.handleChange.bind(this)}
                                        filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>
                                        {
                                            !R.isNil(airlineList) ? airlineList.map(item => {
                                                return (<Select.Option value={item.id + ""}
                                                    key={item.id + ""}>{item.airlineCode}</Select.Option>);
                                            }) : ''
                                        }
                                    </Select>
                                    )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="船公司代码" hasFeedback>
                                {getFieldDecorator('berthingId', {
                                    rules: [{
                                        required: true, message: '请选择船公司代码'
                                    }],
                                    initialValue: (R.isNil(dataSource.berthingId) || R.isEmpty(dataSource.berthingId)) ? undefined : dataSource.berthingId + ""
                                })(
                                    <Select style={{ width: '100%' }} disabled={this.state.disabled} showSearch
                                        placeholder="可通过输入关键字搜索"
                                        filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>
                                        {
                                            !R.isNil(berthingCompanyList) ? berthingCompanyList.map(item => {
                                                return (<Select.Option value={item.id + ""}
                                                    key={item.id + ""}>{item.berthingCode}</Select.Option>);
                                            }) : ''
                                        }
                                    </Select>
                                    )}
                            </FormItem>
                        </Col>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="起运港" hasFeedback>
                                {getFieldDecorator('loadingPort', {
                                    rules: [{
                                        required: true, message: '请选择起运港',
                                    }],
                                    initialValue: dataSource.loadingPort ? dataSource.loadingPort + "" : undefined
                                })(
                                    <Select style={{ width: '100%' }} disabled={this.state.disabled} showSearch
                                        placeholder="可通过输入关键字搜索" onChange={this.handleChange.bind(this)}
                                        filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>
                                        {
                                            !R.isNil(loadingPortList) ? loadingPortList.map(item => {
                                                return (<Select.Option value={item.id + ""}
                                                    key={item.id + ""}>{item.portName + "-(" + item.portCode + ")"}</Select.Option>);
                                            }) : ''
                                        }
                                    </Select>
                                    )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="目的港" hasFeedback>
                                {getFieldDecorator('destinationPort', {
                                    rules: [{
                                        required: true, message: '请选择目的港',
                                    }],
                                    initialValue: dataSource.destinationPort ? dataSource.destinationPort + "" : undefined
                                })(
                                    <Select style={{ width: '100%' }} disabled={this.state.disabled} showSearch
                                        placeholder="可通过输入关键字搜索" onChange={this.handleChange.bind(this)}
                                        filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>
                                        {
                                            !R.isNil(destinationPortist) ? destinationPortist.map(item => {
                                                return (<Select.Option value={item.id + ""}
                                                    key={item.id + ""}>{item.portName + "-(" + item.portCode + ")"}</Select.Option>);
                                            }) : ''
                                        }
                                    </Select>
                                    )}
                            </FormItem>
                        </Col>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="航程(天数)" hasFeedback>
                                {getFieldDecorator('sail', {
                                    rules: [{
                                        required: true, message: '请输入航程',
                                    }],
                                    initialValue: dataSource.sail
                                })(
                                    <InputNumber disabled={this.state.disabled} min={0} max={99999999999999}
                                        maxLength="11" style={{ width: '100%' }} />
                                    )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="船期" hasFeedback>
                                {getFieldDecorator('cutOff', {
                                    rules: [{
                                        required: true, message: '请选择船期',
                                    }],
                                    initialValue: dataSource.cutOff
                                })(
                                    <Input disabled={this.state.disabled} maxLength="30" />
                                    )}
                            </FormItem>
                        </Col>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="是否中转" hasFeedback>
                                {getFieldDecorator('transit', {
                                    rules: [{
                                        required: true, message: '请选择是否中转',
                                    }],
                                    initialValue: dataSource.transit
                                })(
                                    <Select disabled={this.state.disabled} onChange={this.onChangeTransit.bind(this)}>
                                        <Select.Option value="1">是</Select.Option>
                                        <Select.Option value="2">否</Select.Option>
                                    </Select>
                                    )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="中转港" hasFeedback>
                                {getFieldDecorator('transitPort', {
                                    rules: [{
                                        required: this.props.form.getFieldValue('transit') === "1", message: '请选择中转港',
                                    }],
                                    initialValue: dataSource.transitPort && dataSource.transitPort !== 0 ? dataSource.transitPort + "" : undefined
                                })(
                                    <PortSelect disabled={this.state.disabled || this.props.form.getFieldValue("transit") !== "1"} style={{ width: '100%' }} portType={"1"} allowClear />
                                    )}
                            </FormItem>
                        </Col>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="20GP费用" hasFeedback>
                                {getFieldDecorator('fee20gp', {
                                    rules: [{
                                        required: true, message: '请输入20GP费用',
                                    }],
                                    initialValue: dataSource.fee20gp
                                })(
                                    <InputNumber disabled={this.state.disabled} max={99999999999999} maxLength="11" style={{ width: '100%' }} />
                                    )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="40GP费用" hasFeedback>
                                {getFieldDecorator('fee40gp', {
                                    rules: [{
                                        required: true, message: '请输入40GP费用',
                                    }],
                                    initialValue: dataSource.fee40gp
                                })(
                                    <InputNumber disabled={this.state.disabled} max={99999999999999} maxLength="11" style={{ width: '100%' }} />
                                    )}
                            </FormItem>
                        </Col>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="40HQ费用" hasFeedback>
                                {getFieldDecorator('fee40hq', {
                                    rules: [{
                                        required: true, message: '请输入40HQ费用',
                                    }],
                                    initialValue: dataSource.fee40hq
                                })(
                                    <InputNumber disabled={this.state.disabled} max={99999999999999} maxLength="11" style={{ width: '100%' }} />
                                    )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="有效开始时间" hasFeedback>
                                {getFieldDecorator('begindate', {
                                    rules: [{
                                        required: true, message: '请选择有效开始时间'
                                    }],
                                    initialValue: (R.isNil(dataSource.begindate) || R.isEmpty(dataSource.begindate)) ? undefined : moment(dataSource.begindate, dateFormat)
                                })(
                                    <DatePicker disabled={this.state.disabled} style={{ width: '100%' }}
                                        showTime={{ format: 'YYYY-MM-DD' }}
                                        format="YYYY-MM-DD" placeholder="请选择有效开始时间" />
                                    )}
                            </FormItem>
                        </Col>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="有效结束时间" hasFeedback>
                                {getFieldDecorator('enddate', {
                                    rules: [{
                                        required: true, message: '请选择有效结束时间'
                                    }],
                                    initialValue: (R.isNil(dataSource.enddate) || R.isEmpty(dataSource.enddate)) ? undefined : moment(dataSource.enddate, dateFormat)
                                })(
                                    <DatePicker disabled={this.state.disabled} style={{ width: '100%' }}
                                        showTime={{ format: 'YYYY-MM-DD' }}
                                        format="YYYY-MM-DD" placeholder="请选择有效结束时间" />
                                    )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={24}>
                            <FormItem {...layout} label="特价船期" hasFeedback>
                                {getFieldDecorator('specialShipPeriod', {
                                    rules: [{
                                        required: false, message: '请输入特价船期',
                                    }],
                                    initialValue: dataSource.specialShipPeriod
                                })(
                                    <Input disabled={this.state.disabled} maxLength="100" />
                                    )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={24}>
                            <FormItem {...layout} label="备注" hasFeedback>
                                {getFieldDecorator('memo', {
                                    rules: [{
                                        required: false, message: '请输入备注',
                                    }],
                                    initialValue: dataSource.memo
                                })(
                                    <Input.TextArea disabled={this.state.disabled} maxLength="300" autosize={true} />
                                    )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="租户共享">
                                {getFieldDecorator('share', {
                                    valuePropName: 'checked',
                                    initialValue: dataSource.share !== '1'
                                })(
                                    <Switch checkedChildren={'是'} unCheckedChildren={'否'} />
                                    )}
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
            </Modal>
        )
    }
})

function mapStateToProps(state) {
    return {
        loading: state.loading.models.freightFee,
        freightFee: state.freightFee,
        supplier: state.supplier,
        airline: state.airline,
        berthingCompany: state.berthingCompany
    };
}

export default connect(mapStateToProps)(freightFeeDetail);